package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.dao.jdbc.ClassVideoJdbc;
import com.wuseguang.springcloud.dao.jdbc.ClassesJdbc;
import com.wuseguang.springcloud.dao.mapper.ClassVideoMapper;
import com.wuseguang.springcloud.dao.repository.ClassVideoRepository;
import com.wuseguang.springcloud.dao.repository.VideoRepository;
import com.wuseguang.springcloud.entity.ClassVideo;
import com.wuseguang.springcloud.entity.Video;
import com.wuseguang.springcloud.service.ClassVideoService;
import com.wuseguang.springcloud.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 班级视频表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-01-07
 */
@Service
public class ClassVideoServiceImpl implements ClassVideoService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    private ClassVideoRepository classVideoRepository;
    @Autowired
    private ClassVideoMapper classVideoMapper;
    @Autowired
    private ClassVideoJdbc classVideoJdbc;
    @Autowired
    private ClassesJdbc classesJdbc;

    @Autowired
    private ClassCardFieldService service;

    @Autowired
    private ClassCardService classCardService;

    @Override
    public Result addClassVideo(String schoolId, String name, Integer show, Integer pshow, Integer[] classId, String videoUrl, String termId, String teacherName, String teacherId, String videoCover) {
        //创建视频
        Video video = new Video();
        //视频标题
        video.setVideoName(name);
        //视屏封面
        video.setVideoCover(videoCover);
        //视频url
        video.setVideoUrl(videoUrl);
        //发布时间
        video.setOpertime(new Date());
        //学校id
        video.setSchoolId(Integer.valueOf(schoolId));
        //来源
        video.setSource(1);
        //学期
        video.setTermId(Integer.valueOf(termId));
        //是否审核 (后期扩展审核功能，现在默认审核)
        video.setChecks(0);
        //是否显示到班牌首页
        video.setDisplay(show);

        //是否展示给家长小程序
        video.setPdisplay(pshow);

        //发布人
        video.setPublisher(teacherName);
        //发布人id
        video.setTeacherId(Integer.valueOf(teacherId));
        //添加并且获得id
        Integer videoId = videoRepository.save(video).getId();
        //如果为空
        if (StringUtils.isEmpty(videoId)) {
            return new Result(CodeUtil.VIDEO_PUBLISHING);
        }

        String sql = "insert into `system_notification_form` (`type`, `icon`, `publisher_id`, `publisher`, `content`, `class_id`,`opertime`) values(?,?,?,?,?,?,now())";
        //班级(相片/图片)集合
        List<ClassVideo> classVideoList = new ArrayList<ClassVideo>();
        //循环每个班级，跟发布的图片进行绑定
        for (int i = 0; i < classId.length; i++) {
            //创建班级图片
            ClassVideo classVideo = new ClassVideo();
            //班级id
            classVideo.setClassId(classId[i]);
            //视频id
            classVideo.setVideoId(videoId);
            //不置顶
            classVideo.setTop(0);
            //学校id
            classVideo.setSchoolId(Integer.valueOf(schoolId));
            //添加到集合中稍后批量添加
            classVideoList.add(classVideo);

            classesJdbc.updateByParameter(sql, 2, "https://oss.yuguozhijia.online/icon/%E8%A7%86%E9%A2%91%E7%AE%A1%E7%90%86x.png", teacherId, teacherName, name, classId[i]);

            //修改心跳字段 圖片
            service.classesAndCards(classId[i], "videoflag", "1");
            //修改心跳字段  通知
            service.classesAndCards(classId[i], "noticeflag", "1");
        }

        classVideoRepository.saveAll(classVideoList);

        return new Result();
    }

    @Override
    public Result roofPlacementVideo(String id, String teacherId, String admin, String schoolId) {
        logger.info("置顶视频 ClassVideoServiceImpl - > roofPlacementVideo");

        //修改心跳字段
        String sql1 = "SELECT class_id FROM class_video WHERE video_id = ?";
        List<Integer> integers = classesJdbc.queryListInteger(sql1, new Object[]{Integer.valueOf(id)});
        service.classesAndCards(integers, "videoflag", "1");

        //根据id查询视频
        Video video = videoRepository.findById(Integer.valueOf(id)).get();

        //判断是否是发布人
        if (teacherId.equals(video.getTeacherId().toString())) {
            logger.info("这里是发布人");
            //查询这个视频的id
            String sql = "select class_id string from class_video where video_id = ?";
            String classid = classVideoJdbc.queryString(sql, id);
            logger.info("classid = {}", classid);

            //把这些班级的置顶全部改为0
            sql = "UPDATE `class_video` SET `top` = 0 WHERE `class_id` in (?)";
            classVideoJdbc.updateByParameter(sql, classid);

            //把这些班级的置顶全部改为1
            sql = "UPDATE `class_video` SET `top` = 1 WHERE `video_id` = ?";
            classVideoJdbc.updateByParameter(sql, id);
            classCardService.classesAndCards(integers);
            return new Result();
        }

        //查询这个教室是不是年级组长
        List<String> groupLeader = classVideoJdbc.findGradeLeader(teacherId);
        //判断集合大于0时进来
        if (groupLeader.size() > 0) {
            logger.info("年级组长");
            //修改这些班级的置顶
            String sqlOne = "UPDATE `class_video` SET `top` = 0 WHERE `class_id`  in (select id from classes where grade_id = ?)";
            //把这些班级的还有符合图片id的班级置顶
            String sqlTwo = "UPDATE `class_video` SET `top` = 1 WHERE `class_id`  in (select id from classes where grade_id = ?) and video_id =?";
            //循环
            for (String gradeId : groupLeader) {
                //把这些班级改为不置顶
                classVideoJdbc.updateByParameter(sqlOne, gradeId);
                //把这个图片的班级改为置顶
                classVideoJdbc.updateByParameter(sqlTwo, gradeId, id);
            }
            classCardService.classesAndCards(integers);
            return new Result();
        }

        //判断是否是管理员
        if ("0".equals(admin)) {
            //修改这些班级的置顶
            String sqlOne = "UPDATE `class_video` SET `top` = 0 WHERE `school_Id`  = ? and top =1";
            //把这些班级的还有符合图片id的班级置顶
            String sqlTwo = "UPDATE `class_video` SET `top` = 1 WHERE `school_Id`  = ? and video_id =?";
            //把学校置顶的数据改为不置顶
            classVideoJdbc.updateByParameter(sqlOne, schoolId);
            //把学校这个的班级全部改置顶
            classVideoJdbc.updateByParameter(sqlTwo, schoolId, id);
            classCardService.classesAndCards(integers);
            return new Result();
        }


        return new Result(CodeUtil.NO_AUTHORITY);
    }

    @Override
    public Result deleteVideo(String id, String teacherId, String admin) {

        try {
            //修改心跳字段
            String sql1 = "SELECT class_id FROM class_video WHERE video_id = ?";
            List<Integer> integers = classesJdbc.queryListInteger(sql1, new Object[]{Integer.valueOf(id)});
            service.classesAndCards(integers, "videoflag", "1");

            logger.info("删除视频");
            //根据id查询视频
            Video video = videoRepository.findById(Integer.valueOf(id)).get();

            //判断如果是发布人删除全部
            if (teacherId.equals(video.getTeacherId().toString()) || "0".equals(admin)) {
                logger.info("这里是发布人或者管理员");
                //删除班级视频数据
                videoRepository.deleteById(Integer.valueOf(id));
                //删除所有绑定视频的班级
                String sql = "DELETE FROM class_video WHERE `video_id` = ? ";
                classVideoJdbc.updateByParameter(sql, id);
                classCardService.classesAndCards(integers);
                //删除oss中的文件视频
                CallbackSample.deleteFile(video.getVideoUrl());
                CallbackSample.deleteFile(video.getVideoCover());
                return new Result();
            }

            //查询这个教室是不是年级组长
            List<String> groupLeader = classVideoJdbc.findGradeLeader(teacherId);
            //判断集合大于0时进来
            if (groupLeader.size() > 0) {
                logger.info("年级组长");
                //删除这个视频的班级
                String sql = "DELETE FROM `class_video` WHERE `class_id`  in (select id from classes where grade_id = ?)";
                //循环
                for (String gradeId : groupLeader) {
                    classVideoJdbc.updateByParameter(sql, gradeId);
                }
                //再次查询这个视频是否还有班级
                sql = "select COUNT(1) count from class_video where video_id = ? ";
                //获取还有多少条
                int count = classVideoJdbc.queryCount(sql, id);
                //判断如果没有班级绑定这个视频了就把这个视频删除掉
                if (count == 0) {
                    videoRepository.deleteById(Integer.valueOf(id));
                    //删除oss中的文件视频
                    CallbackSample.deleteFile(video.getVideoUrl());
                    CallbackSample.deleteFile(video.getVideoCover());
                }
                classCardService.classesAndCards(integers);
                return new Result();
            }
        } catch (Exception e) {

        }

        logger.info("无权限删除");
        return new Result(CodeUtil.NO_PUBLISHER_NO_CAO_ZU);
    }

    @Override
    public Result findClassVideoList(String[] classId, String termId, String schoolId, Integer indexNo, Integer rows, String admin, String teacherId) {
        logger.info("查询班级视频 ClassVideoServiceImpl - > findClassVideoList");
        //查询符合班级的班牌图片信息
        String sql = null;
        //要查询的班级
        String classid = null;


        //判断班级是否等于null并且是管理员
        if (classId.length == 0 && "0".equals(admin)) {
            sql = "select v.id,v.video_name,v.video_cover,v.video_url,DATE_FORMAT( v.opertime, '%Y-%m-%d' ) opertime,v.publisher ,t.head_portrait ,v.display `show`,v.pdisplay pshow from video v left join teacher t on (t.id=v.teacher_id)  where EXISTS " +
                    "(select * from class_video cv where v.id =cv.video_id )   and v.school_id = ?  ORDER BY v.id desc";
        }
        //判断班级id是否等于空，如果等于空测查询有权限的班级的全部数据
        else if (classId.length == 0) {
            classid = classesJdbc.findClassIds(schoolId, teacherId);
            sql = "select v.id,v.video_name,v.video_cover,v.video_url,DATE_FORMAT( v.opertime, '%Y-%m-%d' ) opertime,v.publisher ,t.head_portrait ,v.display `show` ,v.pdisplay pshow from video v left join teacher t on (t.id=v.teacher_id)  where EXISTS " +
                    "(select * from class_video cv where v.id =cv.video_id and  cv.class_id in (" + classid + ") )  and v.school_id = ?  ORDER BY v.id desc";

        } else {

            //这里表示不是管理员，班级也不为空
            classid = org.apache.commons.lang.StringUtils.join(classId, ",");
            sql = "select v.id,v.video_name,v.video_cover,v.video_url,DATE_FORMAT( v.opertime, '%Y-%m-%d' ) opertime,v.publisher ,t.head_portrait ,v.display `show` ,v.pdisplay pshow from video v left join teacher t on (t.id=v.teacher_id)  where EXISTS " +
                    "(select * from class_video cv where v.id =cv.video_id and  cv.class_id in (" + classid + ") )   and v.school_id = ?  ORDER BY v.id desc";

        }

        //转为String 类型

        //查询视频信息
        List<Map<String, Object>> list = classVideoJdbc.queryListMap(sql, schoolId);

        //
        for (Map<String, Object> map : list) {
            //查询图片的绑定班级信息
            sql = "select c.id,c.`name`name  from classes c  WHERE EXISTS " +
                    "(select * from class_video cv WHERE  c.id=cv.class_id and  cv.video_id = ?)";
            List<Map<String, Object>> classList = classVideoJdbc.queryListMap(sql, map.get("id"));
            map.put("list", classList);
        }

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, tool.getList(), indexNo));
    }
}
